<?php

namespace Backend\Modules\Video\Controllers;

use Library\Constant\Constant;
use Phalcon\Paginator\Adapter\Model as Paginator;
use Phalcon\Mvc\Model\Resultset;
use Library\Pagination\Pager as Pager;
use Backend\Modules\Video\Forms\FormCreateHomeCategory;
use Backend\Modules\Video\Models\Video;
use Backend\Modules\Video\Models\HomeCategory;
use Backend\Modules\Video\Models\HomeVideo;

class HomeCategoryController extends \BackendController
{
	public $urlHomeCategory = 'video/home-category';

	public function indexAction()
	{
        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        $homeCategory = HomeCategory::find();
        $data = array();

        if ($currentPage == 0) {
            $currentPage = 1;
        }
        $pager = new Pager(
            new Paginator(array(
                'data'  => $homeCategory,
                'limit' => Constant::ITEM_PER_PAGE_20 ,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                // Range window will be 5 pages
                'rangeLength' => 5,
                // Just a string with URL mask
                'urlMask'     => '?page={%page_number}',
            )
        );

        $this->view->pager = $pager;
	}

	public function createAction()
	{
		$form = new FormCreateHomeCategory();
        $form->setAction($this->getBackendUrl() . '/' . $this->urlHomeCategory . '/create');

        if($this->request->isPost())
        {
            if($form->isValid($this->request->getPost()) != false)
            {
                $homeCategory = new HomeCategory();
                $dataPost = $this->request->getPost();
                $homeCategory->assign($dataPost);
                if($homeCategory->save())
                {
                    return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlHomeCategory);
                }
                $this->flash->error($homeCategory->getMessages());
            }
        }
        $this->view->form = $form;
	}

    public function editAction($id)
    {
        $this->assets
            ->addJs('vendor/backend/js/video/video_ajax.js')
            ->addJs('vendor/backend/js/video/home_category.js');

        $homeCategory = HomeCategory::findFirstById($id);
        if(!$homeCategory)
        {
            $this->flash->error("Home category was not found");
            return $this->dispatcher->forward(array(
                'action' => 'index'
            ));
        }

        $form = new FormCreateHomeCategory($homeCategory , array('edit' => true));
        $form->setAction($this->getBackendUrl() . '/' . $this->urlHomeCategory . '/edit/' . $id . '?tab=general');
        $tab = $this->request->get('tab') ? $this->request->get('tab') : 'general';
        if($this->request->getPost())
        {
            switch($tab){
                case 'general':
                    if($form->isValid($this->request->getPost()) != false)
                    {
                        $dataPost = $this->request->getPost();
                        $homeCategory->assign($dataPost);

                        if($homeCategory->save())
                        {
                            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlHomeCategory);
                        }
                        $this->flash->error($homeCategory->getMessages());
                    }
                    break;

                case 'video':

                    if($this->request->hasPost('selectedVideoRemove'))
                    {
                        $selectedVideos = $this->request->getPost('selectedVideoRemove');
                        $data = array();
                        foreach($selectedVideos as $videoId)
                        {
                            $homeVideo = HomeVideo::find(array(
                                "home_category_id = $id AND object_id = $videoId AND object_type = 'video'"
                            ))->getFirst();
                            if($homeVideo)
                            {
                                $homeVideo->delete();
                            }
                        }
                    }
                    break;
            }
            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlHomeCategory . '/edit/' . $id . '?tab=' . $tab);
        }

        $homeVideos = $this->modelsManager->createBuilder()
            ->from(array('homeVideo' => '\Backend\Modules\Video\Models\HomeVideo'))
            ->groupBy("homeVideo.id")
            //->join('\Backend\Modules\Video\Models\Video' , 'homeVideo.object_id = video.id' , 'video')
            ->limit(Constant::ITEM_PER_PAGE_20)
            ->where('homeVideo.home_category_id = :home_category_id: AND homeVideo.object_type = :object_type:', array('home_category_id' => $id , 'object_type' => 'video'))
            ->orderBy('homeVideo.position')
            ->getQuery()
            ->execute();

        $homeVideosGroups = $this->modelsManager->createBuilder()
            ->from(array('homeVideo' => '\Backend\Modules\Video\Models\HomeVideo'))
            ->groupBy("homeVideo.id")
            //->join('\Backend\Modules\Video\Models\VideoG' , 'homeVideo.object_id = video.id' , 'video')
            ->limit(Constant::ITEM_PER_PAGE_20)
            ->where('homeVideo.home_category_id = :home_category_id: AND homeVideo.object_type = :object_type:', array('home_category_id' => $id , 'object_type' => 'video_group'))
            ->orderBy('homeVideo.position')
            ->getQuery()
            ->execute();
        
        $this->view->homeVideos = $homeVideos;
        $this->view->homeVideosGroups = $homeVideosGroups;
        $this->view->tab = $tab;
        $this->view->form = $form;
        $this->view->homeCategory = $homeCategory;
    }

    /*
     * Delete video group
     */

    public function deleteAction($id)
    {
        $homeCategory = HomeCategory::findFirstById($id);
        if(!$homeCategory)
        {
            $this->flash->error("Home category was not found");
            return $this->dispatcher->forward(array(
                'action' => 'index'
            ));
        }
        if(!$homeCategory->delete())
        {
            $this->flash->error($homeCategory->getMessages());
        }
        else
        {
            $this->flash->success("Home category was deleted");
        }

        return $this->dispatcher->forward(array(
            'action' => 'index'
        ));
    }
}